<?php

namespace addons\kzvote\controller\store;

use app\common\model\kzvote\Store;
use think\Cookie;
use think\Hook;
use think\Validate;

class Login extends BaseController
{
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;

        //监听注册登录退出的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }
    public function login()
    {
        if ($this->request->isPost()){
            $username = $this->request->post('username/s','');
            $password = $this->request->post('password/s','');

            $rule = [
                'username'   => 'require|length:3,50',
                'password'  => 'require|length:6,30',
            ];

            $msg = [
                'username.require'  => '账号不能为空',
                'username.length'   => '账号必须3-30个字符',
                'password.require' => '密码不能为空',
                'password.length'  => '密码必须6-30个字符',
            ];
            $data = [
                'username'   => $username,
                'password'  => $password,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()));
            }

            $store = Store::get(['username'=>$username]);
            if (!$store) {
                $this->error('账号不存在');
            }

            if ($store->status != '1') {
                $this->error('账号已被禁用');
            }
            if ($store->password != md5(md5($password) . $store->salt)) {
                $this->error('密码错误');
            }

            //直接登录会员
            if ($this->auth->direct($store->user_id)){
                $this->success('登录成功',url('/kzvote'),['token'=>$this->auth->getToken()]);
            }
            $this->error('登录失败');
        }
        return $this->view->fetch();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        if ($this->request->isPost()) {
            $this->token();
            //退出本站
            $this->auth->logout();
            $this->success(__('Logout successful'), url('/kzvote/login'));
        }
        $html = "<form id='logout_submit' name='logout_submit' action='' method='post'>" . token() . "<input type='submit' value='ok' style='display:none;'></form>";
        $html .= "<script>document.forms['logout_submit'].submit();</script>";

        return $html;
    }

}
